<template>
  <view class="user-info-container">
    <view class="header">
      <view class="back-to-home" @click="navigateToIndex">
        <uni-icons type="back" size="24"></uni-icons> 返回首页
      </view>
      <view class="edit-button" @click="toggleEdit">
        <uni-icons :type="isEditing ? 'checkmark' : 'edit'" size="24"></uni-icons> {{ isEditing ? '完成' : '编辑' }}
      </view>
    </view>
    <view v-if="isUserInfoAvailable" class="user-info-container">
      <p v-if="userInfo && userInfo.username !== undefined">
        <uni-icons type="contact" size="30"></uni-icons>
        <strong>用户账号：</strong>
        <input v-if="isEditing" v-model="userInfo.username" />
        <span v-else>{{ userInfo.username }}</span>
      </p>
      <p v-if="userInfo && userInfo.nickName !== undefined">
        <uni-icons type="contact-filled" size="30"></uni-icons>
        <strong>用户昵称：</strong>
        <input v-if="isEditing" v-model="userInfo.nickName" />
        <span v-else>{{ userInfo.nickName }}</span>
      </p>
      <p v-if="userInfo && userType !== undefined">
        <uni-icons type="staff" size="30"></uni-icons>
        <strong>用户类型：</strong>{{ userType }}
      </p>
      <p v-if="userInfo && userInfo.email !== undefined">
        <uni-icons type="email" size="30"></uni-icons>
        <strong>用户邮箱：</strong>
        <input v-if="isEditing" v-model="userInfo.email" />
        <span v-else>{{ userInfo.email }}</span>
      </p>
      <p v-if="userInfo && userInfo.phonenumber !== undefined">
        <uni-icons type="phone" size="30"></uni-icons>
        <strong>手机号码：</strong>
        <input v-if="isEditing" v-model="userInfo.phonenumber" />
        <span v-else>{{ userInfo.phonenumber }}</span>
      </p>
      <!-- 增加对 userInfo 和 userInfo.sex 属性的双重防护 -->
      <p v-if="userInfo && userInfo.sex !== undefined">
        <uni-icons type="person" size="30"></uni-icons>
        <strong>用户性别：</strong>
        <select v-if="isEditing" v-model="userInfo.sex">
          <option value="0">男</option>
          <option value="1">女</option>
        </select>
        <span v-else>{{ gender }}</span>
      </p>
    </view>
  </view>
</template>

<script>
import config from '@/config';

export default {
  data() {
    return {
      isEditing: false,
      userInfo: {
        username: '',
        nickName: '',
        email: '',
        phonenumber: '',
        sex: '',
      },
      userType: '',
      gender: '',
    };
  },
  computed: {
    isUserInfoAvailable() {
      return (
        this.userInfo &&
        this.userInfo.username !== undefined &&
        this.userInfo.nickName !== undefined &&
        this.userInfo.email !== undefined &&
        this.userInfo.phonenumber !== undefined &&
        this.userInfo.sex !== undefined
      );
    },
  },
  mounted() {
    console.log('组件挂载时的 userInfo:', this.userInfo);
    this.getUserInfo();
  },
  methods: {
    getUserInfo() {
      uni.request({
        url: config.apiUrl + '/user/getuserinfo',
        method: 'GET',
        success: (res) => {
          if (res.statusCode === 200 && res.data) {
            const data = res.data;
            console.log('获取到的用户信息:', data);

            // 确保 userInfo 对象存在必要的字段
            this.userInfo = {
              username: data.username || '',
              nickName: data.nickName || '',
              email: data.email || '',
              phonenumber: data.phonenumber || '',
              sex: (data.sex !== undefined && data.sex !== null) ? data.sex : '',
            };

            this.userType = this.userTypeMapping(data.userType);
            this.gender = this.genderMapping(data.sex);

            console.log('最终的 userInfo:', this.userInfo);
          } else {
            console.error('获取用户信息失败，响应数据不正确', res);
          }
        },
        fail: (err) => {
          console.error('获取用户信息失败', err);
        },
      });
    },
    userTypeMapping(type) {
      const typeMap = {
        '00': '游客',
        '01': '会员',
        '02': '管理员',
      };
      return typeMap[type] || '未知类型';
    },
    genderMapping(gender) {
      const genderMap = {
        '0': '男',
        '1': '女',
      };
      return genderMap[gender] || '未知性别';
    },
    navigateToIndex() {
      uni.reLaunch({
        url: '/pages/mine/index',
      });
    },
    toggleEdit() {
      console.log("当前 isEditing 状态:", this.isEditing);
      console.log("toggleEdit 前的 userInfo:", this.userInfo);

      if (this.isEditing) {
        console.log("进入 saveUserInfo");
        this.saveUserInfoSafely();
      } else {
        this.checkAndInitializeUserInfo();
      }

      this.isEditing = !this.isEditing;
      
      console.log("切换后 isEditing 状态:", this.isEditing);
      console.log("toggleEdit 后的 userInfo:", this.userInfo);
    },
    checkAndInitializeUserInfo() {
      this.userInfo = {
        username: this.userInfo.username || '',
        nickName: this.userInfo.nickName || '',
        email: this.userInfo.email || '',
        phonenumber: this.userInfo.phonenumber || '',
        sex: (this.userInfo.sex !== undefined && this.userInfo.sex !== null) ? this.userInfo.sex : '',
      };
      console.log("校验并初始化后的 userInfo 状态:", this.userInfo);
    },
    saveUserInfoSafely() {
      console.log('保存用户信息:', this.userInfo);

      // 再次确保 userInfo 对象的所有属性均已初始化
      this.checkAndInitializeUserInfo();
      
      if (
        !this.userInfo ||
        !this.userInfo.username ||
        !this.userInfo.nickName ||
        !this.userInfo.email ||
        !this.userInfo.phonenumber ||
        this.userInfo.sex === undefined
      ) {
        console.error('用户信息不完整，无法保存');
        return;
      }

      uni.request({
        url: config.apiUrl + '/user/update',
        method: 'PUT',
        data: { ...this.userInfo }, // 复制确保信息的一致性
        success: (res) => {
          if (res.statusCode === 200) {
            uni.showToast({
              title: '用户信息更新成功',
              icon: 'success',
            });
            this.getUserInfo();
          } else {
            uni.showToast({
              title: '用户信息更新失败',
              icon: 'none',
            });
          }
        },
        fail: (err) => {
          console.error('保存用户信息请求失败:', err);
          uni.showToast({
            title: '保存用户信息失败',
            icon: 'none',
          });
        },
      });
    }
  },
};
</script>

<style scoped>
.user-info-container {
  background-color: #f0f0f0;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.user-info-container p {
  margin-bottom: 10px;
  border-bottom: 1px solid #ddd;
  padding-bottom: 5px;
}
.user-info-container strong {
  font-weight: bold;
  margin-right: 5px;
  color: #333;
}
.back-to-home {
  margin-bottom: 10px;
  cursor: pointer;
  color: #007AFF;
}
.back-to-home uni-icons {
  vertical-align: middle;
  margin-right: 5px;
}
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.edit-button {
  cursor: pointer;
}
</style>
